package com.hemi.rhet;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hemi.rhet.MainTabActivity.RefreshListener;
import com.hemi.rhet.PullDownView.OnPullDownListener;
import com.hemi.rhet.html.TopicList;
import com.hemi.rhet.util.ApplicationContext;
import com.hemi.rhet.util.FileUtil;
import com.hemi.rhet.util.HttpUtil;
import com.hemi.rhet.vo.PostImageVo;
import com.hemi.rhet.vo.PostModelVo;
import com.hemi.ui.image.ImageDownloader;

public class TopicsListActivity extends Activity {
    private PullDownView pullDownView;
	private ScrollOverListView listView;
	private MyAdapter adapter;
	private List<PostModelVo> arrays;
	private LayoutInflater inflater;
	private boolean isLoading = false;
	 final static int CANSHU = 1; 


	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initUi();
        
      if(getParent() instanceof MainTabActivity)
      {
    	  MainTabActivity cc =  MainTabActivity.class.cast(getParent());
    	  cc.setOnfreshListener(new RefreshListener(){
		  public void fresh() {
			  if(!isLoading)
			  {
				initUi();
				isLoading=false;
			  }
			  
		  }
    	  });
      }
    }
	
	private void initUi(){
		isLoading=true;
        setContentView(R.layout.activity_main);
        inflater = getLayoutInflater();
        pullDownView = (PullDownView) findViewById(R.id.pulldownview);
        pullDownView.enableAutoFetchMore(true, 0);
        listView = pullDownView.getListView();
        adapter = new MyAdapter();
        listView.setAdapter(adapter);
        initArrays(new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		if(arrays!=null)
        		arrays.clear();
        		arrays = (List<PostModelVo>) msg.obj;
        		adapter.notifyDataSetChanged();
        		pullDownView.notifyDidDataLoad(false);
        		
        	}
        });
        
        pullDownView.setOnPullDownListener(new OnPullDownListener() {
			@Override
			public void onRefresh() { 
                   initArrays(h1);
                   
			}
			
			@Override
			public void onLoadMore() {
				getNextPageArrays(new Handler(){
					@Override
					public void handleMessage(Message msg) {
						List<PostModelVo> ms=  (List<PostModelVo>) msg.obj;
						if(ms!=null)
						arrays.addAll(ms);
						adapter.notifyDataSetChanged();
						pullDownView.notifyDidLoadMore(ms==null || ms.isEmpty() ||ms.size()<15);
					}
				});
			}
		});
        
        isLoading=false;
	}
	Handler h1 = new Handler(){
    	public void handleMessage(Message msg) {
    		if(arrays==null)
    		{
    			arrays=new ArrayList<PostModelVo>();
    		}
        	arrays.clear();
			arrays.addAll(0, (List<PostModelVo>) msg.obj);
			adapter.notifyDataSetChanged();
			pullDownView.notifyDidRefresh(arrays.isEmpty());
			isLoading=false;
		}
    };
    HashMap queryparammap=  new HashMap();
	private void initArrays(final Handler handler) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				 try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					Thread.interrupted();
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				List<String> as = new ArrayList<String>();
				try {
					  List<PostModelVo> ass;
					String urlStr = new StringBuffer(ApplicationContext.DOMAIN+"/post/allPostes_4json").toString();
					
					queryparammap.put("page.begin", "0");
					queryparammap.put("page.eventType", "first");
	 				String  content = HttpUtil.postUrl(urlStr, queryparammap);
	 				Gson gson = new Gson();
	 				Type collectionType = new TypeToken<List<PostModelVo>>(){}.getType(); 
	 				ass= gson.fromJson(content, collectionType);
	 		 
	 				
	 				
	        		handler.obtainMessage(0, ass).sendToTarget();
				} catch (Exception e) {
					Thread.interrupted();
					e.printStackTrace();
				}
				
				
			}
		}).start();
	}
	
	private void getNextPageArrays(final Handler handler) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					  List<PostModelVo> as;
					String urlStr = new StringBuffer(ApplicationContext.DOMAIN+"/post/allPostes_4json").toString();
					queryparammap.put("page.begin", ""+(arrays.size()+1));
					queryparammap.put("page.eventType", "next");
	 				String  content = HttpUtil.postUrl(urlStr, queryparammap);
	 				Gson gson = new Gson();
	 				Type collectionType = new TypeToken<List<PostModelVo>>(){}.getType(); 
	 				as= gson.fromJson(content, collectionType);
	        		handler.obtainMessage(0, as).sendToTarget();
				} catch (Exception e) {
					Thread.interrupted();
					e.printStackTrace();
				}
			}
		}).start();
	}

	  private final ImageDownloader imageDownloader = new ImageDownloader();
	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return arrays == null ? 0 : arrays.size();
		}

		@Override
		public Object getItem(int position) {
			return arrays.get(position);
		}

		@Override
		public long getItemId(int position) {
			return arrays.get(position).getId();
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder=null;
			if (convertView == null) {
				 holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.item_list, null);
				holder.userlogo =(ImageView)  convertView.findViewById(R.id.userImageLogo);
				holder.layout = (LinearLayout) convertView.findViewById(R.id.imagesLayout);
				holder.nrview= (TextView) convertView.findViewById(R.id.postcontent);
				holder.useridview= (TextView) convertView.findViewById(R.id.useridview);
				holder.posttimeview =(TextView)  convertView.findViewById(R.id.posttimeview);
				holder.imageAttr = new ImageView(parent.getContext());
				holder.replycounttext = (TextView)  convertView.findViewById(R.id.count_text_size);
				
				holder.layout.addView(holder.imageAttr);
				convertView.setTag(holder);
			} 
			holder = (ViewHolder)convertView.getTag();
				PostModelVo postVo = 	arrays.get(position);
				holder.nrview.setText(postVo.getNr());
				imageDownloader.download(ApplicationContext.DOMAIN+postVo.getLogo(), holder.userlogo);
				holder.useridview.setText("@"+postVo.getRm());
				holder.posttimeview.setText(postVo.getSj());
				holder.replycounttext.setText("("+postVo.getReplyCount()+")");
				final PostImageVo[] images = postVo.getImags();
				
				holder.imageAttr.setImageDrawable(null);
				if(images!=null)
				{
					holder.imageAttr.setImageDrawable((getResources().getDrawable(R.drawable.image_loading)));
					holder.imageAttr.setOnClickListener(new OnClickListener(){
						public void onClick(View arg0) {
							Activity act= TopicsListActivity.this;
		                	LayoutInflater inflater=act.getLayoutInflater();
		            		View linearlayout= inflater.inflate(R.layout.image_preview, null);
		            		Dialog	dialog  =	new AlertDialog.Builder(act).setView(linearlayout).setIcon(R.drawable.btn_insert_pics_res).create();
		            		   dialog.show();    
		            		WindowManager wm = (WindowManager) act.getSystemService(Context.WINDOW_SERVICE); 
		            		Display display = wm.getDefaultDisplay(); 
		            		final WebView  mWebView  = (WebView) linearlayout.findViewById(R.id.imagePreive_view); 
		            		mWebView.setInitialScale(100);//初始显示比例100%
		            		 WebSettings webSettings = mWebView.getSettings(); 
		                    webSettings.setSavePassword(false);   
		                    webSettings.setSaveFormData(false);   
		                    webSettings.setJavaScriptEnabled(true);   
		                    webSettings.setSupportZoom(true);   
		                    webSettings.setBuiltInZoomControls(true);
		                    ImageView  timg  = (ImageView) linearlayout.findViewById(R.id.image_turn); 
		                    timg.setOnClickListener(new OnClickListener(){
								public void onClick(View arg0) {
									 mWebView.loadUrl("javascript:timage()");
								}
		                    });
		                    String idd = FileUtil.getUniqueId();
		            		mWebView.setBackgroundColor(14737637);
		            		String imageId = "_id"+idd;
		            		HashMap params = new HashMap();
		            		params.put("showImageurl",ApplicationContext.DOMAIN+images[0].getLarg());
		            		params.put("imageId",imageId);
		            		params.put("isIssured","true");
		            		String html=TopicList.createNew().compile(act,"image_preview.template", null,params);
		            		mWebView.loadDataWithBaseURL("file:///android_asset/.", html, "text/html", "utf-8", null);  
						}});
						imageDownloader.download(ApplicationContext.DOMAIN+images[0].getMiddle(), holder.imageAttr);
				} 
			 
			return convertView;
			}
		}
	
	private static class ViewHolder {
		 
		TextView nrview;
		TextView useridview;
		TextView posttimeview;
		TextView replycounttext;
		ImageView userlogo;
		LinearLayout  layout;
		ImageView imageAttr;
	}

	
	}
	
	